package com.invest.utils.security;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Arrays;

public class SignUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignUtils.class);
    private static final String WX_SIGN_DIGEST = "SHA-1";
    /**
     *
     * @param signList
     * @return
     */
	public static String  shaSign(String[] signList) {
		
        try {
            // 将token、timestamp、nonce三个参数进行字典序排序
            Arrays.sort(signList);
            MessageDigest md = MessageDigest.getInstance(WX_SIGN_DIGEST);
            StringBuilder builder = new StringBuilder();
            for(String item : signList){
                builder.append(item);
            }

            // 将三个参数字符串拼接成一个字符串进行sha1加密  
            byte[] digest = md.digest(builder.toString().getBytes());
            return byteToStr(digest).toLowerCase();

        } catch (Exception e) {

            LOGGER.error("签名失败", e);
            return null;
        }  
  
    }

 /*   public static void main(String[] args){
        String[] arr = new String[]{"A","B"};
        System.out.print(ArrayUtils.toString(arr));
    }*/

    /**
     * 将字节数组转换为十六进制字符串 
     *  
     * @param byteArray 
     * @return 
     */  
    private static String byteToStr(byte[] byteArray) {

        if(ArrayUtils.isEmpty(byteArray)){
            return null;
        }

    	StringBuilder builder = new StringBuilder();
        for (byte item : byteArray) {  
        	builder.append(byteToHexStr(item));  
        }  
        return builder.toString();  
    }  
  
    /** 
     * 将字节转换为十六进制字符串 
     *  
     * @param mByte 
     * @return 
     */  
    private static String byteToHexStr(byte mByte) {  
    	
        char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
        char[] tempArr = new char[2];  
        tempArr[0] = digit[(mByte >>> 4) & 0X0F];  
        tempArr[1] = digit[mByte & 0X0F];  
        String s = new String(tempArr);  
        return s;  
        
    } 
}
